import globalStore from "../../store/index"

export function valIsNull(val) {
	return val === null || val === undefined || val === ""
}

//将params中的参数拼接进url中
export function handleUrlParams(url, params) {
	//检查url本身是否带有参数
	let hasParams = url.indexOf("?") > -1
	//检查params是否为空
	let paramsIsNull = valIsNull(params)
	//如果params为空，直接返回url
	if (paramsIsNull) {
		return url
	}
	//如果params不为空，将params拼接进url中
	let paramsStr = ""
	for (let key in params) {
		paramsStr += `${key}=${params[key]}&`
	}
	//去掉最后一个&
	paramsStr = paramsStr.substring(0, paramsStr.length - 1)
	//如果url本身带有参数
	if (hasParams) {
		return `${url}&${paramsStr}`
	} else {
		//url本身不带参数
		return `${url}?${paramsStr}`
	}
}

//旋转canvas
//direction的可取值有：left、right
//canvas为需要旋转的源canvas
//_canvas为旋转好的临时canvas(不会显示在页面上)，用于转为base64或文件流
export function rotateCanvas(canvas, direction, _canvas) {
	let image = _canvas.createImage()
	image.src = canvas.toDataURL()
	return new Promise((resolve, reject) => {
		image.onload = function () {
			try {
				_canvas.width = canvas.width
				_canvas.height = canvas.height
				// 最小 与 最大旋转方向，图片旋转4次后回到原方向
				const minStep = 0
				const maxStep = 3
				// img的高度和宽度不能在img元素隐藏后获取，否则会出错
				let height = image.height
				let width = image.width
				let step = 2
				if (direction === "right") {
					step++
					// 旋转到原位置，即超过最大值
					step > maxStep && (step = minStep)
				} else if (direction === "left") {
					step--
					step < minStep && (step = maxStep)
				}
				// 旋转角度以弧度值为参数
				let degree = (step * 90 * Math.PI) / 180
				let ctx = _canvas.getContext("2d")
				switch (step) {
					case 0:
						_canvas.width = width
						_canvas.height = height
						ctx.drawImage(image, 0, 0)
						break
					case 1:
						_canvas.width = height
						_canvas.height = width
						ctx.rotate(degree)
						ctx.drawImage(image, 0, -height)
						break
					case 2:
						_canvas.width = width
						_canvas.height = height
						ctx.rotate(degree)
						ctx.drawImage(image, -width, -height)
						break
					case 3:
						_canvas.width = height
						_canvas.height = width
						ctx.rotate(degree)
						ctx.drawImage(image, -width, 0)
						break
				}
				resolve(_canvas)
			} catch (error) {
				console.log(error, "error")
				reject(error)
			}
		}
	})
}

//计算两个经纬度之间的距离，单位为米
export function getDistance(lat1, lng1, lat2, lng2) {
	// lat为纬度, lng为经度, 一定不要弄错
	const radLat1 = (lat1 * Math.PI) / 180.0
	const radLat2 = (lat2 * Math.PI) / 180.0
	const a = radLat1 - radLat2
	const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
	let s =
		2 *
		Math.asin(
			Math.sqrt(
				Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2),
			),
		)
	s = s * 6378.137 // EARTH_RADIUS;
	s = (Math.round(s * 10000) / 10000) * 1000
	return s
}

import { GAODE_CONFIG } from "../../config"
import amapFile from "../../plugins/amap-wx.js"
//获取用户所在的位置并转化为地址字符串
export function getLocation(limit) {
	return new Promise((resolve, reject) => {
		//调用微信的接口获取位置
		wx.showLoading({
			title: "正在获取位置",
		})

		wx.getLocation({
			type: "gcj02",
			isHighAccuracy: true,
			success: (res) => {
				//获取到经纬度
				const { latitude, longitude } = res
				if (limit && limit.data.length > 0) {
					let currect = false
					for (const item of limit.data) {
						//计算距离是否在范围之内
						const distance = getDistance(
							latitude,
							longitude,
							item.centerLatitude,
							item.centerLongitude,
						)
						if (distance <= item.distance) {
							currect = true
						}
					}
					if (currect === false) {
						wx.hideLoading()
						wx.showToast({
							title: "请确保在指定的范围之内核验",
							icon: "none",
						})
						reject("请确保在指定的范围之内核验")
						return
					}
				}
				//将经纬度转化为地址
				function covertLongitudeAndLatitude(longitude, latitude) {
					return new Promise((resolve1, reject1) => {
						//调用高德地图api,将获取到的经纬度转化为实际的地址
						const gaode_key = GAODE_CONFIG.key
						const myAmapFun = new amapFile.AMapWX({
							key: gaode_key,
						})
						myAmapFun.getRegeo({
							location: longitude + "," + latitude,
							// location的格式为'经度,纬度'
							success: (data) => {
								wx.hideLoading()
								// const location = data[0].regeocodeData.formatted_address
								const location = {
									latitude,
									longitude,
									formatted_address: data[0].regeocodeData.formatted_address,
									city: data[0].regeocodeData.addressComponent.city,
									district: data[0].regeocodeData.addressComponent.district,
									province: data[0].regeocodeData.addressComponent.province,
									township: data[0].regeocodeData.addressComponent.township,
								}
								resolve({
									location,
									formatted_address: data[0].regeocodeData.formatted_address,
								})
								resolve1(data)
							},
							fail: (info) => {
								console.log(info, "info")
								reject1(info)
								reject(info)
							},
						})
					})
				}
				covertLongitudeAndLatitude
					.call(this, longitude, latitude)
					.catch((err) => {
						//再次尝试
						covertLongitudeAndLatitude
							.call(this, longitude, latitude)
							.catch((err) => {
								reject(err)
								console.log(err, "err")
								wx.hideLoading()
								wx.showToast({
									title: "获取位置失败",
									icon: "none",
								})
							})
					})
			},
			fail: (res) => {
				wx.hideLoading()
				if (res.errno && res.errno === 103) {
					wx.showModal({
						title: "提示",
						content:
							"请点击右上角开启本小程序的定位权限，如果已开启权限请尝试退出小程序重新进入",
						showCancel: false,
					})
				} else if (
					res.errMsg &&
					res.errMsg.indexOf("system permission denied") !== -1
				) {
					wx.showModal({
						title: "提示",
						content:
							"请到系统设置打开微信app的定位权限，如果已开启权限请尝试退出小程序重新进入",
						showCancel: false,
					})
				} else if (
					res.errMsg &&
					res.errMsg.indexOf("ERR_CONNECTION_TIMED_OUT") !== -1
				) {
					wx.showModal({
						title: "提示",
						content: "请尝试将设备的5G网络切换到4G或者使用wifi",
						showCancel: false,
						confirmText: "确定",
					})
				} else {
					wx.showModal({
						title: "提示",
						content: "无法获取位置,请检查定位权限是否已开启。",
						showCancel: false,
						confirmText: "确定",
					})
				}
				console.log(res, "er2222r")
				reject(res)
			},
		})
	})
}

export function valIsEmpty(val) {
	return val === null || val === undefined || val === ""
}

export default {
	valIsNull,
	handleUrlParams,
}

// 根据校务行后台配置的开放页面菜单控制该页面是否显示，如果配置了开启人脸核验，则显示该页面
export async function controlShowPage() {
	let showPage = false
	wx.showLoading({
		title: "加载中",
	})
	try {
		const openPages = await globalStore.getters.openPages()
		for (let openPage of openPages) {
			if (openPage.id === "02f5d079d949455592d305c72cd9a61e") {
				showPage = true
				break
			}
		}
	} finally {
		wx.hideLoading()
	}
	return showPage
}

//校验用户输入的手机号码是否合法
export function checkPhone(phone) {
	const reg = /^1[3456789]\d{9}$/
	return reg.test(phone)
}

